from openai import OpenAI
from fpdf import FPDF
from datetime import datetime
import os, re
from qwen_compatible_client import QwenCompatibleClient
FONT_PATH = r"C:\Windows\Fonts\simhei.ttf"
FONT_NAME = "SimHei"

def safe_filename(s):
    return re.sub(r'[^\w]', '_', str(s)) or "anonymous"

class PsychologicalPDFReport:
    def __init__(self, username=None, initial_emotion=None, final_emotion=None, chat_history=None, suicide_score=None, depression_score=None,client=None):
        self.username = username
        self.initial_emotion = initial_emotion
        self.final_emotion = final_emotion
        self.chat_history = chat_history
        self.suicide_score = suicide_score
        self.depression_score = depression_score
        self.filename = ""
        self.client = client#QwenCompatibleClient.with_openai_api()

    def call_api(self, topic, context, score):
        """使用 DeepSeek AI 按需生成50字以内诊断内容"""
        messages = [
            {"role": "system", "content": "你是专业心理健康评估专家，输出内容要简洁具体，约50字。"},
            {"role": "user", "content":
                f"""请根据如下内容，就「{topic}」提供一句专业评估或建议（不超过55字）：
                用户情绪：初始={self.initial_emotion}，结束={self.final_emotion}；
                评分={score}；
                最近交流内容：{context}"""}
        ]
        try:
            response = self.client.chat.completions.create(
                model="myqwen",
                messages=messages,
                stream=False
            )
            return response.choices[0].message.content.strip()
        except Exception as e:
            return f"【AI接口调用失败：{str(e)}】"

    def gen_report(self, output_dir="reports/", username=None, initial_emotion=None, final_emotion=None, chat_history=None, suicide_score=None, depression_score=None):
        # 优先参数，没有就用self属性
        self.username = username if username is not None else self.username
        self.initial_emotion = initial_emotion if initial_emotion is not None else self.initial_emotion
        self.final_emotion = final_emotion if final_emotion is not None else self.final_emotion
        self.chat_history = chat_history if chat_history is not None else self.chat_history
        self.suicide_score = suicide_score if suicide_score is not None else self.suicide_score
        self.depression_score = depression_score if depression_score is not None else self.depression_score

        # 检查参数
        if not all([self.username, self.initial_emotion, self.final_emotion, self.chat_history is not None, self.suicide_score is not None, self.depression_score is not None]):
            raise ValueError("缺少生成报告所需的全部参数！")

        if not os.path.exists(output_dir): os.makedirs(output_dir)
        pdf = FPDF()
        pdf.add_page()
        pdf.set_auto_page_break(True, 15)
        pdf.add_font(FONT_NAME, '', FONT_PATH, uni=True)
        pdf.set_font(FONT_NAME, '', 28)
        pdf.cell(0, 20, "心理健康综合评估报告", ln=True, align="C")
        pdf.set_font(FONT_NAME, '', 14)
        pdf.cell(0, 10, f"用户：{self.username}", ln=True)
        pdf.cell(0, 10, f"生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True)
        pdf.ln(5)

        def section(title):
            pdf.set_font(FONT_NAME, '', 16)
            pdf.set_text_color(0, 80, 160)
            pdf.cell(0, 10, title, ln=True)
            pdf.set_text_color(0, 0, 0)
            pdf.set_font(FONT_NAME, '', 12)

        # ---------------- 内容 ---------------- #
        dialog_text = "\n".join([f"{w}:{m}" for w, m, _ in self.chat_history[-6:]])

        section("一、情绪状态分析")
        pdf.multi_cell(0, 8, f"初始：{self.initial_emotion}，结束：{self.final_emotion}")
        pdf.multi_cell(0, 8, self.call_api("情绪变化分析", dialog_text, None))

        section("二、自杀风险评估")
        pdf.multi_cell(0, 8, f"得分：{self.suicide_score}")
        pdf.multi_cell(0, 8, self.call_api("自杀风险", dialog_text, self.suicide_score))

        section("三、抑郁风险评估")
        pdf.multi_cell(0, 8, f"得分：{self.depression_score}")
        pdf.multi_cell(0, 8, self.call_api("抑郁风险", dialog_text, self.depression_score))

        section("四、综合干预建议")
        for topic in ["饮食建议", "药物建议", "作息建议", "运动建议", "心理建议"]:
            pdf.multi_cell(0, 8, f"{topic}：")
            pdf.multi_cell(0, 8, self.call_api(topic, dialog_text, self.depression_score if "抑郁" in topic else self.suicide_score))
            pdf.ln(2)

        pdf.set_text_color(80, 80, 120)
        pdf.set_font(FONT_NAME, '', 12)
        pdf.multi_cell(0, 8, "提示：如有严重症状，请联系专业机构。本报告仅作参考。", align="C")

        fname = f"{safe_filename(self.username)}_心理报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
        self.filename = os.path.join(output_dir, fname)
        pdf.output(self.filename)
        return self.filename